﻿using UnityEngine;
using System.Collections;

public class MonsterTarget : MonoBehaviour
{

    public Monster monster;
    private bool move;
    private bool isPortal;
    private Vector3 portalPosition;
    private Obstacle obstacle;
    private float moveTime;
    private Vector3 startPosition;

    // Use this for initialization
    void Start ()
    {
        this.gameObject.GetComponent<Rigidbody> ().detectCollisions = false;
        this.transform.parent = null;
        move = false;
    }
    
    // Update is called once per frame
    void Update ()
    {
        if (move)
        {
            MoveMonster ();
        }
    }

    //碰到障碍物
    void OnTriggerEnter (Collider moveTarget)
    {
        if (moveTarget != null)
        {
            obstacle = moveTarget.gameObject.GetComponent<Obstacle> ();
            if (obstacle != null)
            {
                if (obstacle.obstacleType == ObstacleType.regular)
                {
                    move = false;
                    monster.StopMove ();
                    monster.ChangeDirection ();
                }
                else if (obstacle.obstacleType == ObstacleType.portal)
                {
                    portalPosition = obstacle.gameObject.GetComponent<Portal> ().target.position;
                    isPortal = true;
                }
            }
        }
        
        this.gameObject.GetComponent<Rigidbody> ().detectCollisions = false;
    }

    //移动怪物
    private void MoveMonster ()
    {

        monster.transform.position = Vector3.Lerp (startPosition, this.transform.position, moveTime);

        //移动结束
        if (moveTime >= 1)
        {
            move = false;
            monster.StopMove ();

            //按概率改变方向
            if (Random.Range (0, 10) > 7)
            {
                monster.ChangeDirection ();
            }

            //是否传送
            if (!isPortal)
            {
                monster.transform.position = this.transform.position;
            }
            else
            {
                isPortal = false;
                monster.transform.position = portalPosition;
            }

        }
        moveTime += Time.deltaTime * monster.speed;
    }



    //初始化移动
    public void StartMove ()
    {
        move = true;
        moveTime = 0;
        startPosition = monster.transform.position;
    }

}
